using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Ardal.MSBuildShellExtension.DomainModel.API;

/*
 * Copyright (c) 2007-2008, Thomas Ardal (thomasardalatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace Ardal.MSBuildShellExtension.Configurator
{
    public partial class ExtensionsControl : UserControl
    {
        private IExtension currentSelected;
        private readonly IList<IExtension> extensions;
        public ExtensionsControl()
        {
            InitializeComponent();
            extensions = DomainModelFacade.Instance.Extensions;
            foreach (IExtension extension in extensions)
            {
                extensionsListBox.Items.Add(extension);
            }
            foreach (ITarget target in DomainModelFacade.Instance.Targets)
            {
                targetsListView.Items.Add(target.Title);
            }
            extensionsListBox.Focus();
            if (extensionsListBox.Items.Count > 0)
            {
                extensionsListBox.SelectedIndex = 0;
            }
        }

        private void extensionsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            IExtension extension = (IExtension)extensionsListBox.SelectedItem;
            if (extension != null)
            {
                clearChecked();
                fileExtensionTextBox.Text = extension.FileExtension;
                if (string.IsNullOrEmpty(extension.DotNetVersion))
                {
                    dotNetVersionComboBox.SelectedIndex = 0;
                }
                else
                {
                    dotNetVersionComboBox.SelectedItem = extension.DotNetVersion;
                }
                foreach (ITarget target in extension.Targets)
                {
                    foreach (ListViewItem item in targetsListView.Items)
                    {
                        if (item.Text.Equals(target.Title))
                        {
                            item.Checked = true;
                        }
                    }
                }
                currentSelected = extension;
            }
        }

        private void clearChecked()
        {
            foreach (ListViewItem target in targetsListView.Items)
            {
                target.Checked = false;
            }
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            currentSelected = null;
            StateController.ChangeState(new NewExtensionState(this));
        }

        private class NewExtensionState : IState
        {
            private readonly ExtensionsControl control;
            public NewExtensionState(ExtensionsControl control)
            {
                this.control = control;
            }

            #region IState Members

            public void Activate()
            {
                control.extensionsListBox.SelectedIndex = -1;
                control.fileExtensionTextBox.Text = "";
                control.fileExtensionTextBox.Enabled = true;
                control.dotNetVersionComboBox.SelectedIndex = 0;
                control.dotNetVersionComboBox.Enabled = true;
                control.clearChecked();
                control.newButton.Enabled = false;
                control.removeButton.Enabled = false;
                control.addButton.Enabled = true;
                control.fileExtensionTextBox.Focus();
            }

            #endregion
        }

        private void targetsListView_Validated(object sender, EventArgs e)
        {
            if (currentSelected != null)
            {
                foreach (ListViewItem item in targetsListView.Items)
                {
                    if (item.Checked)
                    {
                        bool found = false;
                        foreach (ITarget target in currentSelected.Targets)
                        {
                            if (target.Title.Equals(item.Text))
                            {
                                found = true;
                                if (currentSelected.ToDeleteTargets.Contains(target))
                                {
                                    currentSelected.ToDeleteTargets.Remove(target);
                                }
                            }
                        }
                        if (!found)
                        {
                            foreach (ITarget t in DomainModelFacade.Instance.Targets)
                            {
                                if (t.Title.Equals(item.Text))
                                {
                                    currentSelected.Targets.Add(t);
                                    currentSelected.Modified = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        IList<ITarget> toRemove = new List<ITarget>();
                        foreach (ITarget target in currentSelected.Targets)
                        {
                            if (target.Title.Equals(item.Text))
                            {
                                toRemove.Add(target);
                            }
                        }
                        foreach (ITarget target in toRemove)
                        {
                            currentSelected.Targets.Remove(target);
                            currentSelected.Modified = true;
                            currentSelected.ToDeleteTargets.Add(target);
                        }
                    }
                }
            }
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (extensionsListBox.SelectedIndex != -1)
            {
                IExtension extension = (IExtension)extensionsListBox.SelectedItem;
                extension.Deleted = true;
                extensionsListBox.Items.Remove(extension);
                StateController.ChangeState(new RemoveExtensionState(this));
            }
        }

        private class RemoveExtensionState : IState
        {
            private readonly ExtensionsControl control;
            public RemoveExtensionState(ExtensionsControl control)
            {
                this.control = control;
            }
            #region IState Members

            public void Activate()
            {
                control.fileExtensionTextBox.Text = "";
                control.dotNetVersionComboBox.SelectedIndex = 0;
                control.clearChecked();
            }

            #endregion
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(fileExtensionTextBox.Text))
            {
                errorProvider1.SetError(fileExtensionTextBox, "File extension cannot be empty.");
                fileExtensionTextBox.Focus();
                return;
            }
            errorProvider1.SetError(fileExtensionTextBox, "");
            if (fileExtensionTextBox.Text.Contains(";"))
            {
                errorProvider1.SetError(fileExtensionTextBox, "File extension cannot contain ';'.");
                fileExtensionTextBox.Focus();
                return;
            }
            errorProvider1.SetError(fileExtensionTextBox, "");
            if (fileExtensionTextBox.Text.StartsWith("."))
            {
                errorProvider1.SetError(fileExtensionTextBox, "Do not start with '.'. Examples: 'targets' or 'csproj'.");
                fileExtensionTextBox.Focus();
                return;
            }
            errorProvider1.SetError(fileExtensionTextBox, "");
            foreach (IExtension extension in extensionsListBox.Items)
            {
                if (extension.FileExtension.Equals(fileExtensionTextBox.Text))
                {
                    errorProvider1.SetError(fileExtensionTextBox, "File extension already added to the extensions list.");
                    fileExtensionTextBox.Focus();
                    return;
                }
            }
            errorProvider1.SetError(fileExtensionTextBox, "");
            if (string.IsNullOrEmpty(dotNetVersionComboBox.Text))
            {
                errorProvider1.SetError(dotNetVersionComboBox, "Select a .NET version.");
                dotNetVersionComboBox.Focus();
                return;
            }
            errorProvider1.SetError(dotNetVersionComboBox, "");
            IList<ITarget> newTargets = new List<ITarget>();
            foreach (ListViewItem target in targetsListView.Items)
            {
                if (target.Checked)
                {
                    newTargets.Add(DomainModelFacade.Instance.FindTargetByTitle(target.Text));
                }
            }
            if (newTargets.Count == 0)
            {
                errorProvider1.SetError(targetsListView, "Select at least one target for the new extension.");
                targetsListView.Focus();
                return;
            }
            errorProvider1.SetError(targetsListView, "");
            StateController.ChangeState(new AddExtensionState(this));
            IExtension newExtension = DomainModelFacade.Instance.AddExtension(fileExtensionTextBox.Text, dotNetVersionComboBox.SelectedItem.ToString(), newTargets);
            newExtension.Modified = true;
            extensionsListBox.Items.Add(newExtension);
            extensions.Add(newExtension);
            extensionsListBox.SelectedItem = newExtension;
        }

        private class AddExtensionState : IState
        {
            private readonly ExtensionsControl control;

            public AddExtensionState(ExtensionsControl control)
            {
                this.control = control;
            }

            #region IState Members

            public void Activate()
            {
                control.fileExtensionTextBox.Enabled = false;
                control.newButton.Enabled = true;
                control.removeButton.Enabled = true;
                control.addButton.Enabled = false;
            }

            #endregion
        }

        private void targetsListView_VisibleChanged(object sender, EventArgs e)
        {
            targetsListView.Items.Clear();
            foreach (ITarget target in DomainModelFacade.Instance.Targets)
            {
                targetsListView.Items.Add(target.Title);
            }
            if (currentSelected != null)
            {
                foreach (ITarget target in currentSelected.Targets)
                {
                    foreach (ListViewItem item in targetsListView.Items)
                    {
                        if (item.Text.Equals(target.Title))
                        {
                            item.Checked = true;
                        }
                    }
                }
            }
        }

        private void dotNetVersionComboBox_Validated(object sender, EventArgs e)
        {
            if (currentSelected != null)
            {
                currentSelected.DotNetVersion = dotNetVersionComboBox.SelectedItem.ToString();
            }
        }
    }
}
